package dse.messages.multiversion;

import java.util.*;
import dse.*;
import dse.messages.*;

public class UpdateSuccessV3MessageHandler extends MessageSender implements
		MessageHandler {
	private DataObject dobj;
	private Version version;
	
	public UpdateSuccessV3MessageHandler(Experiment experiment, DataObject dobj, Version version)
	{
		super(experiment);
		this.dobj = dobj;
		this.version = version;
	}
	
	@Override
	public boolean acceptMessage(Message message) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public void messageInterupted(ExperimentRecorder recorder, Message message,
			double time) {
		// TODO Auto-generated method stub
		;
	}

	@Override
	public void messageReceived(ExperimentRecorder recorder, Message message,
			double time) {
		// TODO Auto-generated method stub
		recorder.debug(this, "msgRcvd: " + message, time);
		if (message.messageType() != MessageType.UpdateSuccessV3) {
			recorder.warn(
					"UpdateSucessV3MessageHandler recieved " + 
					message.messageType() + " message."
					);
			return;
		}
		
		Node vs = message.to();
		vs.updateSuccess(version, dobj);
		if(vs.dataVersions.get(dobj).get(version) >= dobj.shareCount())
		{
			LinkedList<Node> residentNodes = MessageUtil.getNodesByDht(experiment.network(), 
					vs, dobj, experiment.modules().assigner());
			for(Node node : residentNodes)
			{
				Message m = super.createRemoveOldShareV3Message(vs, node, dobj, 
						version, MessagePurpose.DataObjectUpdate);
				recorder.debug(this, "new msg: " + m, time);
				experiment.messageQueue().enqueueMessage(m, time);
			}
			
			//NavigableSet<Version> versions = vs.dataVersions.get(dobj).headSet(version, true);
			//if(versions != null){
				//for(Version v : versions){
			vs.dataVersions.get(dobj).remove(version);
				//}
			//}
		}
	}
}